package org.zj.webview.type;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * ui task
 * 因为dll中为了最大化引用数量使用全局弱引用，这里必须要暂存runnable对象
 *
 * @author zj
 * @since 2025/7/1
 */
public class UiTask implements Runnable {
    private static final Set<Runnable> RUNNABLE = Collections.synchronizedSet(new HashSet<>());

    private final Runnable runnable;

    public UiTask(Runnable runnable) {
        RUNNABLE.add(this.runnable = runnable);
    }

    @Override
    public void run() {
        try {
            this.runnable.run();
        } finally {
            RUNNABLE.remove(this.runnable);
        }
    }

    /**
     * ui task callback
     */
    public static class Callback extends UiTask {

        private final Runnable callback;

        public Callback(Runnable runnable, Runnable callback) {
            super(runnable);
            this.callback = callback;
        }

        @Override
        public void run() {
            try {
                super.run();
            } finally {
                callback.run();
            }
        }
    }
}
